package com.csea.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.TypeReference;
import java.util.List;
import java.util.Map;

/**
 * JSON工具类，基于FastJSON2实现对象与JSON之间的转换
 */
public class JsonUtil {

    // 默认序列化特性（Fastjson2版本）
    private static final JSONWriter.Feature[] DEFAULT_SERIALIZER_FEATURES = {
//            JSONWriter.Feature.UseDateFormat,              // 日期格式化
//            JSONWriter.Feature.DisableCircularReferenceDetect // 禁用循环引用检测
    };

    public static String toJson(Object obj) {
        return toJson(obj, DEFAULT_SERIALIZER_FEATURES);
    }

    public static String toJson(Object obj, JSONWriter.Feature... features) {
        if (obj == null) return null;
        return JSON.toJSONString(obj, features);
    }

    public static JSONObject toJsonObject(String json) {
        return JSON.parseObject(json);
    }

    public static JSONArray toJsonArray(String json) {
        return JSON.parseArray(json);
    }

    public static <T> T toObject(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    public static <T> T toObject(String json, TypeReference<T> typeReference) {
        return JSON.parseObject(json, typeReference);
    }

    public static <T> List<T> toList(String json, Class<T> elementType) {
        return JSON.parseArray(json, elementType);
    }

    public static Map<String, Object> toMap(Object obj) {
        return JSON.parseObject(toJson(obj), new TypeReference<Map<String, Object>>() {});
    }

    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        return toObject(toJson(map), clazz);
    }

    public static boolean isValidJson(String json) {
        try {
            JSON.parse(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String prettyFormat(String json) {
        try {
            return JSON.toJSONString(JSON.parse(json), JSONWriter.Feature.PrettyFormat);
        } catch (Exception e) {
            return json;
        }
    }
}